package com.xingkeduo.business.order.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingkeduo.business.order.domain.OrderDomainService;
import com.xingkeduo.business.order.remote.CommentRemoteService;
import com.xingkeduo.business.order.remote.MessagePushService;
import com.xingkeduo.business.order.remote.StoreRemoteService;
import com.xingkeduo.business.order.remote.WaitLineRemoteService;
import com.xingkeduo.business.order.remote.feign.StoreFeignService;
import com.xingkeduo.business.order.service.IdGenerateService;
import com.xingkeduo.business.order.service.OrderService;
import com.xingkeduo.delayQueue.model.TaskModel;
import com.xingkeduo.delayQueue.model.TaskModelEnum;
import com.xingkeduo.delayQueue.service.TaskService;
import com.xingkeduo.dto.StoreRemoteDto;
import com.xingkeduo.pojo.query.OrderMapper;
import com.xingkeduo.pojo.query.OrderOldMapper;
import com.xingkeduo.pojo.table.Order;
import com.xingkeduo.pojo.table.OrderOld;
import com.xingkeduo.send.RabbitMqSender;
import com.xingkeduo.utils.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author chi  2019-02-22 16:36
 **/
@RestController
@Slf4j
public class TestController {


    @Resource
    private TaskService taskService;
    @Resource
    private IdGenerateService idGenerateService;
    @Resource
    private CommentRemoteService commentRemoteService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    StoreFeignService storeFeignService;

    @Resource
    WaitLineRemoteService waitLineRemoteService;
    @Resource
    MessagePushService mssagePushService;
    @Resource
    RabbitMqSender rabbitMqSender;

    @Resource
    private OrderOldMapper orderOldMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService orderService;
/*
    @RequestMapping("/create")
    public String create(String record) {
        System.out.println("创建订单插入数据");
        System.out.println("record==" + record);
        final Long ttl = 5000L;
        OrderDetailResponseDto order = new OrderDetailResponseDto();
        order.setUserId("122");
        rabbitTemplate.convertAndSend("order.user.register.delay.exchange", "", JSON.toJSONString(order), new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME,order.getUserId());
                message.getMessageProperties().setExpiration(ttl + "");
                return message;
            }
        }, this.initCorrelationData());
        return "创建订单";
    }


    private CorrelationData initCorrelationData() {
        return new CorrelationData(UUID.randomUUID().toString());
    }

    //直接消费模式
    @RabbitListener(queues = "order.user.register.queue")
    public void consumeMessage(@Payload String sendMessage, Channel channel, Message message) {
        try {
            log.info("消费者监听交易记录信息： {} ", sendMessage);
            log.info("时间过期，已经到ttl了，却还没付款，则需要处理为失效");
        } catch (Exception e) {
            log.error("消息体解析 发生异常； ", e.fillInStackTrace());
        }
    }

    @RequestMapping("/test")
    public String get(String id) {
        CommentsResponseDto comment = commentRemoteService.getComment(123456L);
        return comment.toString();
    }*/


    @RequestMapping("/order/queue/add")
    public String aa() throws Exception {

        taskService.addToDeplayQueue(new TaskModel("1", TaskModelEnum.test));

        Thread.sleep(1000L);

        taskService.addToDeplayQueue(new TaskModel("2", TaskModelEnum.close_order));

        Thread.sleep(1000L);

        taskService.addToDeplayQueue(new TaskModel("3", TaskModelEnum.test));

        Thread.sleep(1000L);

        return "true";
    }


    @RequestMapping("/order/getWaitLineNo")
    public String get(String str) {

        String waitLineNo = waitLineRemoteService.getWaitLineNo(str, LocalDateTime.now());

        return waitLineNo;
    }

    @Resource
    OrderDomainService orderDomainService;

    @RequestMapping("/order/pushMessage")
    public String pushMessage() {
        String sdlfkj = orderDomainService.qrcodeUrl("23432", "sdlfkj");

        return sdlfkj;
    }


    @RequestMapping("/order/test/lambda")
    public String lambda(String a) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        IPage<Order> page = new Page<>(0, 500);
        IPage<Order> orderIPage = orderMapper.selectPage(page, queryWrapper);

        List<Order> list = orderIPage.getRecords();

        long l1 = System.nanoTime();

        BigDecimal zero = BigDecimal.ZERO;
        for (Order order : list) {
            zero = zero.add(order.getAllPrice());
        }
        System.out.println(zero);


        long l2 = System.nanoTime();

        Optional<BigDecimal> reduce = list.stream().map(order -> {
            return order.getAllPrice();
        }).reduce(BigDecimal::add);

        System.out.println(reduce.get());

        long l3 = System.nanoTime();
        long la = l2 - l1;
        long lb = l3 - l2;

        System.out.println(l1);
        System.out.println(l2);
        System.out.println(l3);

        return la + "  " + lb;
    }


    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @RequestMapping("/order/redisLock")
    public String redisLock() throws Exception{

        RedisLock lock = new RedisLock(redisTemplate, "aaa");

        lock.lock();
        System.out.println("进入lock方法=============");

        Thread.sleep(10000);

        lock.unlock();

        System.out.println("*************");

        return "";
    }


    @RequestMapping("/order/redisLock1")
    public String redisLock1() throws Exception{

        RedisLock lock = new RedisLock(redisTemplate, "aaa");

        lock.lock();
        System.out.println("+++++++++++");

        return "";
    }

    @Resource
    StoreRemoteService storeRemoteService;

    @GetMapping("/unCheck/order")
    public String unCheck(String storeId) {
        StoreRemoteDto byStoreId = storeRemoteService.getByStoreId(storeId);
        return JSON.toJSONString(byStoreId);
    }


    @GetMapping("/orderOld")
    public String orderOld(String userId, String adminId) {

        String orderLabels = orderService.getLabels(userId, adminId);


        return orderLabels;
    }




}
